// pages/cart/cart.js
import {
    getSetting,
    chooseAddress,
    openSetting,
    showModal,
    showToast
} from "../../utils/asyncWx.js"
import regeneratorRuntime from '../../lib/runtime/runtime';
Page({

    /**
     * 页面的初始数据
     */
    data: {
        address: {},
        cart: [],
        goodsChecked:false,
        allChecked: false,
        totalPrice: 0,
        totalNum: 0,
        edit: false,
        checkGoods: [],
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onShow: function (options) {
        // 获取缓存中的收获地址
        const address = wx.getStorageSync('address')
        // 获取缓存中的购物车数据  
        const cart = wx.getStorageSync('cart') || []
        // every 数组方法 会遍历 会接收一个回调函数 那么每一个回调函数都返回true 那么every的返回值就是true
        // 只要有一个回调函数返回了false 那么不再循环执行了，直接返回false
        // 空数组调用every返回值就是true
        // const allChecked = cart.lenght?cart.every(v=>v.checked):false
        // 给data赋值
        this.setData({
            cart,
            address,
            goodsChecked:false,
            allChecked: false,
        })

    },
    // 设计购物车信息 计算总价格 总数量 全选标志
    setCart(cart = this.data.cart) {
        const {checkGoods} = this.data;
        let check = [];
        checkGoods.forEach(v=>{
            check.push(...cart.filter(i=>i.goods_id==v));
        });
        //总价格 总数量
        let totalPrice = 0,totalNum = 0;
        cart.forEach(v=>v.banMinus = v.num > 1 ? false : true);
        check.forEach(v => {
            totalPrice += v.goods_price * v.num;
            totalNum += v.num;
        });        
        this.setData({
            cart,
            totalPrice,
            totalNum
        })
        wx.setStorageSync('cart', cart)
    },

    // 点击添加收货地址按钮
    async handleChooseAddress() {
        // 调用内置api 获取用户收货地址
        // 获取用户对小程序 所授予获取地址的 权限状态 scope authSetting scope.address
        // 未获得权限，引导用户授权再获取地址
        //把获取到的收货地址存入到本地存储中
        try {
            // 获取权限状态的
            const res1 = await getSetting()
            const scopeAddress = res1.authSetting["scope.address"]
            if (scopeAddress === false) {
                // 用户 以前 拒绝过授予权限，先引导用户授予权限
                await openSetting()
            }
            let address = await chooseAddress()
            // 把地址存入本地存储
            address.allAddresss = address.cityName + address.countyName + address.detailInfo
            wx.setStorageSync('address', address)

        } catch (error) {
            console.log(error)
        }
    },
    // 商品选中按钮
    handleItemChange(e) {
        const {
            id
        } = e.target.dataset;
        let {checkGoods,cart,allChecked} = this.data;
        const i = checkGoods.findIndex(v => v === id);
        if (i === -1) {
            checkGoods.push(id);
        } else {
            checkGoods.splice(i, 1);
        }
        allChecked = cart.length==checkGoods.length?true:false;
        this.setData({
            allChecked,
            checkGoods
        });
        this.setCart();
    },
    // 商品的全选功能
    handleItemAllCheck() {
        let allChecked = !this.data.allChecked;
        let goodsChecked = allChecked;
        let checkGoods = [];
        const cart = wx.getStorageSync('cart')||[];
        if (allChecked) {
            cart.forEach(v => checkGoods.push(v.goods_id));
        }
        this.setData({
            goodsChecked,
            allChecked,
            checkGoods
        });
        this.setCart();
    },
    // 商品数量
    handleGoodsNum(e) {
        const {
            id,
            option
        } = e.currentTarget.dataset
        let {
            cart
        } = this.data
        const index = cart.findIndex(v => v.goods_id === id)
        if (cart[index].banMinus && option === -1) return;
        cart[index].num += option;
        this.setCart(cart);
    },
    // 购物车编辑按钮开启关闭
    handleEditGoods() {
        const edit = !this.data.edit
        this.setData({
            edit
        })
    },
    // 购物车开启编辑后的删除商品
    handleDeleteGoods() {
        let {
            cart,
            allChecked,
            checkGoods
        } = this.data
        wx.showModal({
            title: '删除商品',
            content: '您确定要删除选中商品吗？',
            success: (res) => {
                if (res.confirm) {
                    if (allChecked) {
                        cart = []
                    } else {
                        checkGoods.forEach(v => cart = cart.filter(i => i.goods_id != v));
                    }
                    this.setCart(cart);
                    this.setData({allChecked:false,checkGoods:[]});
                    wx.showToast({
                      title: '删除成功',
                      icon:'success',
                      mask:true
                    });
                }
            }
        });
    },
    // 移入收藏夹
    handleCollectGoods() {
        let {
            cart,
            checkGoods
        } = this.data
        let collect = wx.getStorageSync('collect') || []
        let goods = [];
        wx.showModal({
            title: '收藏商品',
            content: '您确定要将选中商品移入收藏夹吗？',
            success: (res) => {
                if(res.confirm) {
                    checkGoods.forEach(v=>{
                        goods.push(...cart.filter(i=>i.goods_id==v));
                        cart = cart.filter(i=>i.goods_id!=v);
                        collect = collect.filter(i=>i.goods_id!=v);
                    });
                    collect = [...goods,...collect];
                    wx.setStorageSync('collect', collect);
                    this.setCart(cart);
                    this.setData({allChecked:false,checkGoods:[]});
                    wx.showToast({
                        title: '移入成功',
                        icon:'success',
                        mask:true
                      });
                }
            }
        })
    },
    // 购物车结算
    async handleBuyGoods() {
        // 判断收货地址
        let {
            cart,
            totalNum,
            address,
            checkGoods
        } = this.data
        // checkGoods = JSON.stringify(checkGoods);
        if (cart.length === 0) {
            await showToast({title: '未添加商品',icon: 'error',mask:true});
            return;
        } else if (totalNum === 0) {
            await showToast({title: '未选中商品',icon: 'error',mask:true});
            return;
        } else if (!address.userName) {
            await showToast({title: '未添加地址',icon: 'error',mask:true});
            return;
        } else {
            wx.navigateTo({
                url: '/pages/pay/pay?checkGoods='+checkGoods,
            });
        }
    }
})